<template>
  <BasicModal v-bind="$attrs" @register="registerModal" destroyOnClose :title="title" width="60%" @ok="handleSubmit">
    <a-row>
      <a-col span="24">
        <a-steps :current="current" class="steps-flow">
          <a-step v-for="item in steps" :key="item.title" :title="item.title" :description="item.description" />
        </a-steps>
        <div class="steps-content scbz_box">
          <!-- <a-col span="12" style="margin: auto">
            <BasicForm @register="registerForm">
          </a-col> -->
          <a-col span="12" style="margin: auto;"  v-if="current == 0">
            <div class="lb_item">
              <div class="lb_tit">种植计划：<span>*</span></div>
              <div class="kuang">
                <a-select
                      ref="select"
                      v-model:value="value1"
                      @focus="focus"
                      @change="handleChange"
                    >
                      <a-select-option :value="item.value" v-for="(item,index) in options1" :key="ndex">{{item.label}}</a-select-option>
                    </a-select>
              </div>
              <div class="wxts">请选择种植计划!</div>
            </div>
            <div class="lb_item">
              <div class="lb_tit">农事操作：<span>*</span></div>
              <div class="kuang">
                <a-select
                      ref="select"
                      v-model:value="value1"
                      @focus="focus"
                      @change="handleChange"
                    >
                      <a-select-option :value="item.value" v-for="(item,index) in options1" :key="ndex">{{item.label}}</a-select-option>
                    </a-select>
              </div>
              <div class="wxts">请选择农事操作!</div>
            </div>
          </a-col>
          <a-col span="12" style="margin: auto;" v-if="current == 1">
            <div class="lb_item">
              <div class="lb_tit">投入品：</div>
              <div class="kuang">
                <a-select
                      ref="select"
                      v-model:value="value1"
                      style="width: 120px"
                      @focus="focus"
                      @change="handleChange"
                    >
                      <a-select-option :value="item.value" v-for="(item,index) in options1" :key="ndex">{{item.label}}</a-select-option>
                    </a-select>
              </div>
            </div>
            <div class="lb_item">
              <div class="lb_tit">作业要求：</div>
              <div class="kuang kuang1">
                <a-textarea v-model:value="value" placeholder="请输入作业要求"  />
              </div>
            </div>
            <div class="lb_item">
              <div class="lb_tit">生产标准：</div>
              <div class="kuang  sousuo">
                <a-input v-model="keyword" placeholder="请输入搜索生产标准关键字" type="text" id="" class="ant-input"
                  @change="changeWord" @pressEnter="searchWord" />
                <div class="ss_icon" @click="searchWord">
                  <img class="ss_icon_img" src="/icn_ss.png" alt="">
                </div>
              </div>
              <div class="lb_item_ts">提示：点击生产标准即可展开看全部，点击 “ + ” 即可快捷添加作业要求。</div>
              <div class="">
                <div style="display: flex;justify-content: space-between;align-items: center;"
                  v-for="(item,index) in scbz_arr" :key="item.title">
                  <div class="kuang scbz_item" :class="item.selected ? 'scbz_item1': ''" @click="choice1(index)">
                    {{item.title}}
                  </div>
                  <div class="lb_item_jia" @click="choice(index)" :class="item.selected ? 'lb_item_jia1': ''">
                    <svg class="lb_item_jia_img" xmlns="http://www.w3.org/2000/svg"
                      xmlns:xlink="http://www.w3.org/1999/xlink" width="21" height="21" viewBox="0 0 21 21" fill="none">
                      <path id="并集" fill-rule="evenodd" style="fill:#E5E7EB" opacity="1"
                        d="M0 9L0 12L9 12L9 21L12 21L12 12L21 12L21 9L12 9L12 0L9 0L9 9L0 9Z"></path>
                    </svg>
                  </div>
                </div>
              </div>
            </div>
          </a-col>
          <a-col span="12" style="margin: auto;" v-if="current == 2">
            <div class="lb_item">
              <div class="lb_tit">作业开始时间</div>
              <div class="kuang">
                <a-space direction="vertical">
                    <a-date-picker
                      v-model:value="value12"
                      format="YYYY-MM-DD HH:mm:ss"
                      :disabled-date="disabledDate"
                      :disabled-time="disabledDateTime"
                      :show-time="{ defaultValue: dayjs('00:00:00', 'HH:mm:ss') }"
                    />
                  </a-space>
              </div>
              <div class="wxts">请选择作业开始时间!</div>
            </div>
            <div class="lb_item">
              <div class="lb_tit">计划操作人<span>*</span></div>
              <div class="jhczr">
                <a-checkbox-group v-model:value="state.checkedList" :options="plainOptions" />
              </div>
              <div class="wxts">请选择计划操作人!</div>
            </div>
          </a-col>
        </div>
      </a-col>
    </a-row>
    <template #footer>
      <div class="steps-action">
        <a-button v-if="current > 0" style="margin-right: 8px" @click="prev">上一步</a-button>
        <a-button v-if="current < steps.length - 1" type="primary" @click="next">下一步</a-button>
        <a-button v-if="current == steps.length - 1" type="primary" @click="handleSubmit">
          提交
        </a-button>
      </div>
    </template>
  </BasicModal>
</template>

<script lang="ts" setup>
  import dayjs, { Dayjs } from 'dayjs';
  import { ref, computed, unref, nextTick, watch, watchEffect, reactive } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema } from '../TProductionSchedule.data';
  import { saveOrUpdate, createProductionScheduleByTemplateId } from '../TProductionSchedule.api';
  import { list } from "/@/views/planting-process/productionScheduleTemplate/ProductionScheduleTemplate.api";
  import { defHttp } from "/@/utils/http/axios";

  import type { SelectProps } from 'ant-design-vue';
  const value1 = ref('请选择投入品');
  const options1 = ref<SelectProps['options']>([
    {
      value: 'a1',
      label: '肥料001',
    },
    {
      value: 'a2',
      label: '肥料002',
    }
  ]);
  const focus = () => {
    console.log('focus');
  };

  const range = (start : number, end : number) => {
    const result = [];

    for (let i = start; i < end; i++) {
      result.push(i);
    }

    return result;
  };

  const disabledDate = (current : Dayjs) => {
    return current && current < dayjs().endOf('day');
  };

  const disabledDateTime = () => {
    return {
      disabledHours: () => range(0, 24).splice(4, 20),
      disabledMinutes: () => range(30, 60),
      disabledSeconds: () => [55, 56],
    };
  };
  const value12 = ref<Dayjs>();

  const plainOptions = ['cng', 'jcjguser', '张三', 'jeecg', '张小红12'];
  const state = reactive({
    indeterminate: true,
    checkAll: false,
    checkedList: ['cng', '张小红12'],
  });
  const handleChange = (value : string) => {
    console.log(`selected ${value}`);
  };
  // Emits声明
  const emit = defineEmits(['register', 'success']);
  const isUpdate = ref(true);

  // 步骤条配置
  const current = ref<number>(0);
  const next = () => {
    // validateForm(true);
    current.value++
  };
  const prev = () => {
    current.value--;
  };

  const validateForm = (type) => {
    let valid;
    switch (current.value) {
      case 0:
        valid = validateFields(['growPlanId', 'productionOperation']);
        break;
      case 1:
        valid = validateFields(['input', 'operationDescription']);
        break;
      case 2:
        valid = validateFields(['jobStartTime', 'jobUsers']);
        break;
    }
    valid.then(values => {
      type ? current.value++ : current.value--;
    }).catch(err => {
      console.log(err)
    })
  }

  // 分别展示表单项
  // watch(current, (v) => {
  //   switch (v) {
  //     case 0:
  //       hiddenField(['growPlanId', 'productionOperation']);
  //       break;
  //     case 1:
  //       getProductionStandard('');
  //       hiddenField(['input', 'operationDescription']);
  //       break;
  //     case 2:
  //       hiddenField(['jobStartTime', 'jobUsers']);
  //       break;
  //   }
  // })
  const scbz_arr = ref();
  const getProductionStandard = (word : string) => {
    const formData = getFieldsValue();
    if (formData.growPlanId && formData.productionOperation) {
      defHttp.get({
        url: "/productionStandard/getStandByProductionOperationAndGrowPlan", params: {
          growPlanId: formData.growPlanId,
          productionOperation: formData.productionOperation,
          keyWord: word || ''
        }

      }).then(res => {
        scbz_arr.value = [];
        res.records.map(item => {
          scbz_arr.value.push({
            title: item.content,
            selected: false
          })
        })
      })
    }
  }

  const keyword = ref();
  const changeWord = (e) => {
    keyword.value = e.target.value;
  }
  const searchWord = () => {
    getProductionStandard(keyword.value)
  }

  const hiddenField = (fields, render = 1) => {
    formSchema.map((item) => {
      if (fields.includes(item.field)) {
        render ? updateSchema({ field: item.field, show: true }) : item.show = true;
      } else {
        render ? updateSchema({ field: item.field, show: false }) : item.show = false;
      }
    })
  }
  const choice = (index) => {
    scbz_arr.value[index].selected = !scbz_arr.value[index].selected
    let content = getFieldsValue().operationDescription || '';
    if (scbz_arr.value[index].selected) {
      content += scbz_arr.value[index].title
    } else {
      content = content.replace(scbz_arr.value[index].title, '');
    }
    setFieldsValue({ operationDescription: content })
  }

  const choice1 = (index) => {
    scbz_arr.value[index].selected = !scbz_arr.value[index].selected
  }
  const steps = [
    {
      title: '做什么？',
      description: '选择农事类型',
      content: 'First-content',
    },
    {
      title: '有无投入品？',
      description: '选投入品',
      content: 'Second-content',
    },
    {
      title: '任务分工',
      description: '指派人和时间',
      content: 'Last-content',
    },
  ];
  const items = steps.map(item => ({ key: item.title, title: item.title }));

  const cardData = ref([]);
  const pagination = {
    total: 0,
    showQuickJumper: true,
    onChange: (page : number) => {
      pageList({ pageSize: 5, pageNo: page })
    },
    pageSize: 5,
  };

  hiddenField(['growPlanId', 'productionOperation'], 0);

  // formSchema.map((item) => {
  //   if (item.field == 'productionOperation') {
  //     item.componentProps.onchange = (e) => {
  //       console.log(e)
  //     }
  //   }
  // })

  //表单配置
  // const [registerForm, { setProps, resetFields, setFieldsValue, validate, updateSchema, validateFields, getFieldsValue }] = useForm({
  //   labelWidth: 120,
  //   schemas: formSchema,
  //   showActionButtonGroup: false,
  //   baseColProps: { span: 24 }
  // });
   const formData = ref({
     growPlanId: '',
     productionOperation: '',
     input: '',
     operationDescription: '',
     jobStartTime: '',
     jobUsers: ''
   })
   
   const resetFields = () => {
     Object.keys(formData.value).map(key => {
       formData.value[key] = ''
     })
   }
   
   const setFieldsValue = (data) => {
     Object.keys(formData.value).map(key => {
       if (data.hasOwnProperty(key)) {
         formData.value[key] = data[key]
       }
     })
   }

  //表单赋值
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    if (data && data.record) {
      data.record.growPlanId = data.record.growPlanId.toString();
    }
    //重置表单
    resetFields();
    setModalProps({ confirmLoading: false, showCancelBtn: !!data?.showFooter, showOkBtn: !!data?.showFooter });
    isUpdate.value = !!data?.isUpdate;
    current.value = data?.current || 0
    if (unref(isUpdate)) {
      //表单赋值
      setFieldsValue({
        ...data.record,
      });
      console.log(formData.value)
    } else {
      pageList({ pageSize: 5, pageNo: 1 })
    }
    // 隐藏底部时禁用整个表单
    // setProps({ disabled: !data?.showFooter })
  });
  //设置标题
  const title = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));
  //表单提交事件
  async function handleSubmit(v) {
    try {
      let values = await validate();
      values.jobUsers = values.jobUsers.split(',')
      setModalProps({ confirmLoading: true });
      //提交表单
      await saveOrUpdate(values, isUpdate.value);
      //关闭弹窗
      closeModal();
      //刷新列表
      emit('success');
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
  async function pageList(page) {
    list(page).then(res => {

      cardData.value = res.records;
      pagination.total = res.total;
    })
  }


  async function handleClick(item) {
    // 这里是你处理点击事件的代码
    createProductionScheduleByTemplateId({ templateId: item.id })
      .then(async res => {
        await nextTick();
        await resetFields();
        await setFieldsValue({ ...res })
      })
  }
</script>

<style lang="less">
  .scbz_item {
    padding: 4px 20px;
    line-height: 30px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    cursor: pointer;
    color: rgba(0, 0, 0, 0.45);
    width: 90%;
    transition: all 0.5s;

  }

  .lb_tit {
    margin-left: 10px;
  }

  .scbz_item1 {
    height: auto !important;
    white-space: wrap;
    border: 1px solid #40a9ff;
    color: #40a9ff;
    box-shadow: 0px 2px 2px rgba(24, 144, 255, 0.25);
  }

  .scbz_item:hover {
    border: 1px solid #40a9ff;
    color: #40a9ff;
    box-shadow: 0px 2px 2px rgba(24, 144, 255, 0.25);
  }

  .lb_item {
    margin-bottom: 30px;

    &_ts {
      font-size: 10px;
      color: #FF9233;
      padding: 20px 10px 0px;
    }

    span {
      color: #FF4D4F;
      margin-right: 10px;
    }

    &_jia {
      width: 36px;
      height: 36px;
      border-radius: 50%;
      background: #FFF;
      border: 1px solid #E5E7EB;
      // line-height: 40px;
      text-align: center;
      font-size: 1.5rem;
      color: #E5E7EB;
      transition: all 0.5s;
      cursor: pointer;
      position: relative;

      &_img {
        width: 15px;
        height: 15px;
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
      }
    }

    &_jia:hover {
      border: 1px solid #40a9ff;
      box-shadow: 0px 2px 2px rgba(24, 144, 255, 0.25);
    }

    &_jia:hover>&_jia_img path {
      fill: #40a9ff !important;
    }

    &_jia1 {
      transform: rotate(45deg);
    }
  }

  .jhczr {
    margin-top: 6px;
  }

  .lb_item .jhczr span {
    margin-right: 0px;
    color: #333;
  }

  .kuang {
    height: 40px;
    opacity: 1;
    border-radius: 2px;
    background: #FFFFFF;
    border: 1px solid #E5E7EB;
    margin-top: 6px;
  }

  .kuang>.ant-select {
    width: 100% !important;
    height: 100% !important;
  }

  .kuang>.ant-select>.ant-select-selector {
    width: 100% !important;
    height: 100% !important;
    border: none;
  }

  .kuang>.ant-select>.ant-select-selector #rc_select_7 {
    height: 100%;
  }

  .kuang>.ant-select>.ant-select-selector .ant-select-selection-item {
    height: 100%;
    line-height: 40px;
  }

  .kuang:hover {
    border: 1px solid #40a9ff;
    color: #40a9ff;
    box-shadow: 0px 2px 2px rgba(24, 144, 255, 0.25);
  }

  .kuang .ant-space,
  .kuang .ant-space-item,
  .kuang .ant-picker {
    width: 100% !important;
    height: 100% !important;
    border: none;
  }

  .kuang1 {
    height: 180px;
  }

  .kuang1>.ant-input {
    width: 100%;
    height: 100%;
    border: none;
  }

  .wxts {
    color: #ED6F6F;
    margin-left: 10px;
    font-size: 12px;
    margin-top: 10px;
  }

  .scbz_list {
    display: flex;
    flex-wrap: wrap;

  }

  #scbz_item {
    margin: 5px;
    line-height: 36px;
    padding: 0px 15px;
    background: #fff;
    color: rgba(0, 0, 0, 0.6);
    border: 1px solid #E5E7EB;
    box-sizing: border-box;
    border-radius: 4px;
    cursor: pointer;
    transition: border-color .5s;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  #scbz_item:hover {
    border: 1px solid #40a9ff !important;
    color: #40a9ff !important;
    box-shadow: 0px 2px 2px rgba(24, 144, 255, 0.25);
  }

  .scbz_item_active {
    border: 1px solid #40a9ff !important;
    color: #40a9ff !important;
  }

  .steps-flow {
    width: 75%;
    margin: 30px auto;
  }

  /** 时间和数字输入框样式 */
  :deep(.ant-input-number) {
    width: 100%
  }

  :deep(.ant-calendar-picker) {
    width: 100%
  }

  // 步骤条样式
  .steps-content {
    margin-top: 16px;
    // border: 1px dashed #e9e9e9;
    border-radius: 6px;
    // background-color: #fafafa;
    min-height: 200px;
    // text-align: center;
    padding-top: 60px;
    min-height: 500px;
  }

  .steps-action {
    margin-top: 24px;
    text-align: right;
  }

  .sousuo {
    position: relative;

    .ant-input {
      height: 100%;
      border: none;
    }

    .ss_icon {
      position: absolute;
      height: 70%;
      width: 50px;
      top: 50%;
      right: 0;
      bottom: 0;
      border-left: 1px solid #eee;
      transform: translateY(-50%);
      cursor: pointer;
    }

    .ss_icon_img {
      width: 20px;
      height: 20px;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
    }
  }

  [data-theme='dark'] .steps-content {
    background-color: #2f2f2f;
    border: 1px dashed #404040;
  }

  @media (max-width: 1550px) {
    .steps-flow {
      width: 100%;
      margin: 30px auto;
    }
  }

  @media (max-width: 1366px) {
    .scbz_box>.ant-col-12 {
      max-width: 70%;
    }
  }

  html,
  body {
    font-family: PingFang SC;
  }
</style>
